<?php
include("./config/session-action.php");
include("./config/config.inc.php");

/*上传文件操作*/
class CUserVmUpload extends JsonBase
{
	private $mysqli	= null;
	private $file		= null;
	/* 构造函数 */
	function OnPageLoad() {
		global $mysql_server, $mysql_user, $mysql_passwd, $mysql_database;
		
		// 上传文件 
		if(  !isset($_FILES["file"]) ){
			$this->json["msg"] = "上传文件失败";
			return;
		}
		// 连接数据库
		$server = explode(":", $mysql_server, 2);
		$this->mysqli = new mysqli($server[0], $mysql_user, $mysql_passwd, $mysql_database, isset($server[1])?$server[1]:3306);
		if( mysqli_connect_errno() ){
			$this->json["msg"] = "连接数据库失败";
			$this->mysqli = null;
			return;
		}
		$this->mysqli->autocommit(FALSE);
		// 打开文件
		$this->file = fopen($_FILES["file"]["tmp_name"], "r");
		if( !$this->file ){
			$this->json["msg"] = "读取文件失败";
			return;
		}
		$count = 0;
		// 分析文件, 格式：[用户单位]\t[联系邮箱]\t[联系电话]\t[到期日期(年-月-日)]
		while( $row = fscanf($this->file, "%s\t%s\t%s\t%s\r\n") ){
			$company = str_replace("'", "''", $row[0]);
			$email = str_replace("'", "''", $row[1]);
			$phone = str_replace("'", "''", $row[2]);
			$lastdt = str_replace("'", "''", $row[3]);
			$sql = "insert into t_user_vm2(company,email,phone,lastdt) values('{$company}','{$email}','{$phone}','{$lastdt}')";
			if( !$this->mysqli->query($sql) ){
				$this->json["msg"] = "添加行\"{$row[0]} {$row[1]} {$row[2]} {$row[3]}\"失败";
				return;
			}
			$count ++;
		}
		$this->json["success"] = true;
		$this->json["msg"] = "导入记录{$count}条";
	}
	/* 析构函数 */
	function __destruct() {
		// 关闭MYSQL
		if( $this->mysqli ){
			if(true == $this->json["success"])
				$this->mysqli->commit();
			else
				$this->mysqli->rollback();
			$this->mysqli->close();
		}
		// 关闭文件
		if( $this->file ){
			fclose($this->file);
		}
		// 输出结果
		parent::__destruct();
	}
}

set_time_limit(0);
$cc = new CUserVmUpload();

?>